package com.mlming.springboot.controller;

import com.github.pagehelper.PageInfo;
import com.mlming.springboot.consts.MallConst;
import com.mlming.springboot.form.OrderAddForm;
import com.mlming.springboot.pojo.User;
import com.mlming.springboot.service.OrderService;
import com.mlming.springboot.util.JWTUtil;
import com.mlming.springboot.vo.OrderVo;
import com.mlming.springboot.vo.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

@RestController
public class OrderController {

    @Autowired
    private OrderService orderService;

    @GetMapping("/order")
    public ResponseVo<OrderVo> addOrder(@Valid OrderAddForm orderAddForm,
                                        HttpServletRequest request) {
        String token = request.getHeader(MallConst.TOKEN_NAME);
        Integer userId = Integer.valueOf(JWTUtil.getFieldValuePayLoad(token, MallConst.USER_ID_IN_PAYLOAD));
        return orderService.createOrder(userId,orderAddForm.getShippingId());
    }

    @GetMapping("/orders")
    public ResponseVo<PageInfo> getOrderList(@RequestParam(required = false,defaultValue = "10") Integer pageSize,
                                             @RequestParam(required = false,defaultValue = "1") Integer pageNum,
                                             HttpServletRequest request) {
        String token = request.getHeader(MallConst.TOKEN_NAME);
        Integer userId = Integer.valueOf(JWTUtil.getFieldValuePayLoad(token, MallConst.USER_ID_IN_PAYLOAD));
        return orderService.getOrderList(userId,pageSize,pageNum);
    }

    @GetMapping("/orders/{orderNo}")
    public ResponseVo<OrderVo> getOrderDetail(@PathVariable("orderNo") Long orderNo,
                                              HttpServletRequest request) {
        String token = request.getHeader(MallConst.TOKEN_NAME);
        Integer userId = Integer.valueOf(JWTUtil.getFieldValuePayLoad(token, MallConst.USER_ID_IN_PAYLOAD));
        return orderService.getOrderDetail(userId,orderNo);
    }

    @PutMapping("/orders/{orderNo}")
    public ResponseVo<OrderVo> cancelOrder(@PathVariable("orderNo") Long orderNo,
                                           HttpServletRequest request) {
        String token = request.getHeader(MallConst.TOKEN_NAME);
        Integer userId = Integer.valueOf(JWTUtil.getFieldValuePayLoad(token, MallConst.USER_ID_IN_PAYLOAD));
        return orderService.cancelOrder(userId,orderNo);
    }
}
